# -*- coding: utf-8 -*-
"""
@CreateTime: 2019/12/7 13:36
@Describe: rabbitMq 基类
@Author: cjh
"""
import rabbitpy


class RabbitBase:
    """
    rabbitMq 基类
    """
    def __init__(self, host, port, user, pwd, v_host, queue, exchange_type='direct'):
        """
        :param str host: 主机
        :param str port: 端口
        :param str user:  用户
        :param str pwd: 用户密码
        :param str v_host: 虚拟主机
        :param str queue: 队列名称
        :param str exchange_type: 交换机类型
        """
        self.count = 0
        self.threads_num = 100
        self._queue_name = queue
        self._exchange = queue
        self.connection = rabbitpy.Connection('amqp://{}:{}@{}:{}/{}'.format(user, pwd, host, port, v_host))
        self.channel = rabbitpy.AMQP(self.connection.channel())  # 使用适配器

        self.channel.exchange_declare(exchange=self._exchange, exchange_type=exchange_type, durable=True)  # 声明 exchange
        self.channel.queue_declare(queue=self._queue_name, durable=True)  # 声明队列
        # 绑定队列与exchange
        self.channel.queue_bind(queue=self._queue_name, exchange=self._exchange, routing_key=self._queue_name)

    def publish(self, msg):
        """rabbitMQ publish"""
        self.channel.basic_publish(exchange='', routing_key=self._queue_name, body=msg)

    def clear(self):
        """rabbitMQ purge"""
        self.channel.queue_purge(self._queue_name)

    def get_message_count(self):
        """rabbitMQ get message num"""
        channel = self.connection.channel()
        queue = rabbitpy.amqp_queue.Queue(channel, self._queue_name)
        queue.durable = True
        self.count = queue.declare(passive=True)[0]
        channel.close()

    def get_message(self):
        """
        获取并处理队列内数据 可重写
        :return:
        """
        pass

